package com.docker.sys.app;

import com.docker.core.constant.MainConstant;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import kit.docker.convert.ConvertKit;
import kit.docker.exception.BaseException;
import kit.docker.redis.RedisConstant;
import kit.docker.redis.RedisKit;
import kit.docker.web.APIResCode;

import java.util.Map;

public class AppRedis {

    private static String getCacheName() {
        return MainConstant.REDIS_DOCKER;
    }

    private static String buildAppKey(String appId) {
        return RedisConstant.SYS_APP_SECRET + appId;
    }

    public static AppBean getApp(String appId) {
        if (!RedisKit.exists(getCacheName(), buildAppKey(appId))) {
            throw new BaseException(APIResCode.API_SECURITY_PROTOCOL_AUTHENTICATION_FAILED, "应用授权失败,请联系管理员");
        }
        Map<String, String> map = RedisKit.hgetAll(getCacheName(), buildAppKey(appId));
        AppBean appBean = ConvertKit.mapToObjectStr(map, AppBean.class);
        if (!StrKit.notNull(appBean)) {
            throw new BaseException(APIResCode.API_SECURITY_PROTOCOL_AUTHENTICATION_FAILED, "应用访问失败，请联系管理员");
        }
        return appBean;
    }

    public static void clear() {
        RedisKit.delByPattern(getCacheName(), RedisConstant.SYS_APP_SECRET + "*");
    }

    public static void save(Record app) {
        RedisKit.hmset(getCacheName(), buildAppKey(app.getStr("app_id")), ConvertKit.mapTomap(app.getColumns()));
    }

}
